package com.zpark.user;


import com.zpark.user.bean.User;
import com.zpark.user.utils.JDBCUtils;
import lombok.SneakyThrows;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 登录业务：
 *      1、用户输入登录信息
 *      2、用户点击登录按钮
 *      3、后台获取用户登录数据
 *      4、校验数据
 *      5、根据登录名字查询数据
 *          如果查询有结果，则比较密码是否一致，一致则登录成功，否则，登录失败
 *          如果查询没有结果，则登录失败
 *      6、响应登录结果
 */
@WebServlet("/user/login.do")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户登录数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 校验数据（使用正则表达式校验）

        // 根据登录名字查询数据 select username, password, sex, language, city from user where username=?
        // 获取数据库连接对象
        Connection conn = JDBCUtils.getConnection();
        String sql = "select id, username, password, sex, language, city from user where username=?";
        // 获取执行sql预编译对象
        PreparedStatement stat = conn.prepareStatement(sql);
        // 替换占位符
        stat.setString(1, username);

        // 执行sql语句
        ResultSet rest = stat.executeQuery();
        // 将rest结果封装到user对象当中
        User user = null;
        while (rest.next()) {
            // 取出数据
            user = new User();
            user.setUsername(rest.getString("username"));
            user.setId(rest.getInt("id"));
            user.setPassword(rest.getString("password"));
            user.setSex(rest.getString("sex"));
            user.setLanguage(rest.getString("language"));
            user.setCity(rest.getString("city"));
        }
        // 获取转发器
        RequestDispatcher requestDispatcher = null;
        // 判断是否有结果
        if (user == null) {
            // 登录失败 login_error.html
            // 转发到指定页面
            requestDispatcher = request.getRequestDispatcher("/WEB-INF/html/login_error.html");
            requestDispatcher.forward(request, response);
        }else{
            // 比较密码是否一致
            if (user.getPassword().equals(password)) {
                // 密码一致，则登录成功 login_success.html
                requestDispatcher = request.getRequestDispatcher("/WEB-INF/html/login_success.html");
                requestDispatcher.forward(request, response);
            }else {
                // 登录失败 login_error.html
                requestDispatcher = request.getRequestDispatcher("/WEB-INF/html/login_error.html");
                requestDispatcher.forward(request, response);
            }
        }

    }
}
